
package com.wlsk.license.service.zpff;

import com.alibaba.fastjson.JSONObject;
import com.wlsk.license.common.utils.HttpUtils;
import com.wlsk.license.common.utils.PropertiesUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class RtabTokenHelper {

    public static final String KEY;

    // 运管请求用户名
    public static final String USERNAME;

    private static final Logger LOGGER = LoggerFactory.getLogger(RtabHelper.class);

    private static final String PASSWORD;

    private static final Map<String, String> LOGIN_PARAMS = new HashMap<>();

    private static final Object TOKEN_LOCK = new Object();

    private static Token token = null;

    static {
        try {
            KEY = PropertiesUtils.get("charter.apply.key").trim();
            USERNAME = PropertiesUtils.get("charter.apply.username").trim();
            PASSWORD = PropertiesUtils.get("charter.apply.password").trim();
            LOGIN_PARAMS.put("username", USERNAME);
            LOGIN_PARAMS.put("password", PASSWORD);
            log.info("证牌系统相关配置加载：KEY-{}, USERNAME-{}, PASSWORD-{}", KEY, USERNAME, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getToken() {
        synchronized (TOKEN_LOCK) {
            if (Objects.isNull(token) || !token.whetherEffective()) {
                LocalDateTime effectiveTime = LocalDateTime.now();
                String tokenStr = getTokenFromRtab();
                LOGGER.info("new token -> {}", tokenStr);
                Token newToken = new Token();
                newToken.setToken(tokenStr);
                newToken.setEffectiveTime(effectiveTime);
                newToken.setExpiredTime(effectiveTime.plusMinutes(40));
                token = newToken;
            }
            return token.getToken();
        }
    }

    public static void updateToken(String oldToken) {
        synchronized (TOKEN_LOCK) {
            if (Objects.nonNull(token) && token.getToken().equals(oldToken)) {
                LOGGER.info("update token -> {}", oldToken);
                token = null;
            }
        }
    }

    private static String getTokenFromRtab() {
        String reqStr = JSONObject.toJSONString(LOGIN_PARAMS);
        try {
            String response = HttpUtils.sendTextPost(CharterApplyLicense.login, reqStr);
            Map<String, Object> map = JSONObject.parseObject(response, Map.class);
            String code = (String) map.get("code");
            if ("200".equals(code)) {
                return (String) map.get("token");
            } else {
                LOGGER.warn("There was an error getting the token.--{}", map);
                throw new RuntimeException("获取token失败，响应错误");
            }
        } catch (IOException e) {
            throw new RuntimeException("获取token错误", e);
        }
    }

    @Data
    private static class Token {

        private String token;

        private LocalDateTime effectiveTime;

        private LocalDateTime expiredTime;

        public boolean whetherEffective() {
            return LocalDateTime.now().isBefore(expiredTime);
        }
    }
}
